package com.hs.shirodemo2.shiro;

import com.hs.shirodemo2.entity.SysPermission;
import com.hs.shirodemo2.entity.SysUser;
import com.hs.shirodemo2.entity.UserInfo;
import com.hs.shirodemo2.service.SysPermissionService;
import com.hs.shirodemo2.service.SysRoleService;
import com.hs.shirodemo2.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName CustomRealm
 * @Description 自定义的Realm
 */
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    SysRoleService service;
    @Autowired
    SysPermissionService sysPermissionService;
    @Autowired
    SysUserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        HashSet<String> roleCodes = service.findRoleCodeById(userInfo.getId());
        List<SysPermission> permissionByUserId = sysPermissionService.findPermissionByUserId(userInfo.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleCodes);
        Set<String> permissions = permissionByUserId.stream().map(SysPermission::getPercode).collect(Collectors.toSet());
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        SysUser sysUser = userService.findByUsername(userName);
        UserInfo userInfo = new UserInfo();
        if(sysUser == null) {
            return null;
        }
        BeanUtils.copyProperties(sysUser,userInfo);
        return new SimpleAuthenticationInfo(userInfo,userInfo.getUserpwd(),
                ByteSource.Util.bytes(userInfo.getSalt()), this.getName());
    }
}
